﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using Yipusoft.BaseDoc.Model;
using Yipusoft.Account.Model;

public partial class Task_BaseDoc_DocumentUpLoad : System.Web.UI.Page
{
    private string DepartmentID = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        UserInfo us = Yipusoft.Account.BLL.User.GetUser(Page.User.Identity.Name);
        string usid = us.UserID;
        List<RoleInfo> lr = Yipusoft.Account.BLL.User.GetRoleList(usid);
        bool role = false;
        foreach (RoleInfo r in lr)
        {
            if (r.RoleID == "100199")
            {
                role = true;
                break;
            }
        }

        if (role && Session["TempDepartmentID"] != null)
        {
            DepartmentID = Session["TempDepartmentID"].ToString();
        }
        else
        {
            DepartmentID = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        }

 	if (!IsPostBack)
        {
            BindDepartmentList();
            bindDate();
            Bind();
            Order();
        }
    }

    void BindDepartmentList()
    {

        if (DepartmentID.Substring(0, 4) == "1300")
        {
            trDepartment.Visible = false;
        }
        else if (DepartmentID.Substring(4, 1) == "0")//支队
        {
            trDepartment.Visible = true;
            string where = " Departmentid like '13000" + DepartmentID.Substring(5, 1) + "%' ";
            List<DepartmentInfo> departments = Yipusoft.Account.BLL.Department.GetList(where);
            cblDepartment.DataSource = departments;
            cblDepartment.DataBind();

        } if (DepartmentID.Substring(4, 1) != "0")//大中队
        {
            trDepartment.Visible = true;
            string where = " Departmentid like '" + DepartmentID.Substring(0, 4) + "0%' and right(DepartmentID,3)<>'000' ";
            List<DepartmentInfo> departments = Yipusoft.Account.BLL.Department.GetList(where);
            cblDepartment.DataSource = departments;
            cblDepartment.DataBind();
        }

    }

    private void Bind()
    {
        if (!IsPostBack)
        {
            if (Request["ID"] != "00000000-0000-0000-0000-000000000000" && Request["ID"] != null)
            {
                DocumentFileInfo FileInfo = Yipusoft.BaseDoc.BLL.FileManager.GetFile(new Guid(Request["ID"]));
                YearList.SelectedValue = FileInfo.StartDate.Value.Year.ToString();
                MonthList.SelectedValue = FileInfo.StartDate.Value.Month.ToString();
                DayList.SelectedValue = FileInfo.StartDate.Value.Day.ToString();
            }
        }
        BindParent();
        if (!IsPostBack)
        {
            if (Request["ID"] != null || Request["ID"] != "00000000-0000-0000-0000-000000000000")

                dptParent.SelectedValue = Request["ID"];

        }
        //时间的改变
        selectDate();


    }

    private void BindParent()
    {
        dptParent.Items.Clear();
        
        List<Yipusoft.BaseDoc.Model.DocumentFileInfo> list = Yipusoft.BaseDoc.BLL.FileManager.GetList(" IsFolder='True' And DepartmentID='" + DepartmentID + "' And ParentID='" + Guid.Empty + "' and Year(startDate)=" + YearList.SelectedValue + " and month(startDate)=" + MonthList.SelectedValue + " Order by OrderID ");
        foreach (DocumentFileInfo file in list)
        {
            dptParent.Items.Add(new ListItem("".PadLeft(2 * file.Level.Value, '　') + file.OldFileName, file.ID.ToString()));
            OrderItem(file.ID, file.OldFileName);
        }
        dptParent.Items.Insert(0, new ListItem("临时文件夹", "00"));

    }

    void selectDate()
    {
        if (dptParent.SelectedIndex != 0)
        {
            DocumentFileInfo FileInfo = Yipusoft.BaseDoc.BLL.FileManager.GetFile(new Guid(dptParent.SelectedValue));
            YearList.SelectedValue = FileInfo.StartDate.Value.Year.ToString();
            MonthList.SelectedValue = FileInfo.StartDate.Value.Month.ToString();

        }
    }
    void setParent()
    {
        BindParent();
        
        DateTime startDate = Convert.ToDateTime(YearList.SelectedValue + "-" + MonthList.SelectedValue + "-1");
        List<Yipusoft.BaseDoc.Model.DocumentFileInfo> list = Yipusoft.BaseDoc.BLL.FileManager.GetList(" IsFolder='True' And DepartmentID='" + DepartmentID + "' And ParentID='" + Guid.Empty + "' and Year(startDate)=" + YearList.SelectedValue + " and month(startDate)=" + MonthList.SelectedValue + "  Order by OrderID ");

        if (list.Count > 0)
        {
            dptParent.SelectedValue = list[0].ID.ToString();
        }
        else
        {

        }
    }
    void bindDate()
    {
        YearList.Items.Clear();
        for (int i = 2009; i <= 2050; i++)
        {
            YearList.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }

        MonthList.Items.Clear();
        for (int i = 1; i <= 12; i++)
        {
            MonthList.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }

        DayList.Items.Clear();
        for (int i = 1; i <= 31; i++)
        {
            DayList.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }
        YearList.SelectedValue = DateTime.Now.Year.ToString();
        MonthList.SelectedValue = DateTime.Now.Month.ToString();
        DayList.SelectedValue = DateTime.Now.Day.ToString();
    }
    private void OrderItem(Guid ID, string oldFileName)
    {
        List<Yipusoft.BaseDoc.Model.DocumentFileInfo> list = Yipusoft.BaseDoc.BLL.FileManager.GetList(" IsFolder='True'  And ParentID='" + ID + "' Order by OrderID ");
        if (list != null)
        {
            foreach (DocumentFileInfo info in list)
            {
                dptParent.Items.Add(new ListItem("".PadLeft(2 * info.Level.Value, '　') + info.OldFileName, info.ID.ToString()));
                OrderItem(info.ID, info.OldFileName);
            }
        }

    }

    private void Order()
    {
        for (int i = 1; i <= 50; i++)
        {
            dptOrder.Items.Add(new ListItem(i.ToString()));
        }
    }


    protected void btnUpload_Click(object sender, EventArgs e)
    {
        lblPrompt.Text = "";
        SaveImages();

        if (dptParent.SelectedValue != "00")
        {
            Yipusoft.BaseDoc.BLL.FileManager.UpdateFileSize(new Guid(dptParent.SelectedValue));

        }
        lblPrompt.Text = "上传已成功";
    }

    private Boolean SaveImages()
    {
        
        ///'遍历File表单元素
        HttpFileCollection files = HttpContext.Current.Request.Files;
        if (files.Count < 1)
        {

            lblPrompt.Text = "请您选择要上传的附件";
            return false;

        }
        /// '状态信息

        //try
        //{
        Guid ParentID = Guid.Empty;
        if (dptParent.SelectedValue != "00")
        {
            ParentID = new Guid(dptParent.SelectedValue);
        }


        for (int iFile = 0; iFile < files.Count; iFile++)
        {
            ///'检查文件扩展名字
            HttpPostedFile postedFile = files[iFile];
            string fileName, fileExtension, fileTitle;
            fileTitle = System.IO.Path.GetFileName(postedFile.FileName);
            if (fileTitle != "")
            {
                fileExtension = System.IO.Path.GetExtension(fileTitle);

                string mapPath = "\\MyDocument\\" + DepartmentID + "\\";
                fileName = Server.MapPath("~" + mapPath);
                if (!Directory.Exists(fileName))
                {
                    Directory.CreateDirectory(fileName);
                }
                //fileName += fileTitle;
                ///'可根据扩展名字的不同保存到不同的文件夹
                ///注意：可能要修改你的文件夹的匿名写入权限。
                string temp = Guid.NewGuid() + fileExtension;
                fileName += temp;
                postedFile.SaveAs(fileName);

                DocumentFileInfo info = new DocumentFileInfo();
                info.ID = Guid.NewGuid();
                info.IsFolder = false;
                info.LastAccessDate = DateTime.Now;
                if (ParentID != Guid.Empty)
                {
                    info.Level = Yipusoft.BaseDoc.BLL.FileManager.GetFile(new Guid(dptParent.SelectedValue)).Level + 1;
                }
                else
                {
                    info.Level = 0;
                }
                info.NewFileName = temp;
                info.OldFileName = fileTitle;
                info.OrderID = int.Parse(dptOrder.SelectedValue);

                info.ParentID = ParentID;
                DateTime startDate = Convert.ToDateTime(YearList.SelectedValue + "-" + MonthList.SelectedValue + "-" + DayList.SelectedValue);
                info.StartDate = startDate;

                info.FilePath = mapPath + temp;
                info.FileSize = postedFile.ContentLength / 1024;
                info.Format = fileExtension.Replace(".", "");
                info.HasChild = false;
                info.CreateDate = DateTime.Now;
                info.CreateUser = User.Identity.Name;
                info.DepartmentID = DepartmentID;
                Yipusoft.BaseDoc.BLL.FileManager.AddFile(info);

                //上报上级单位
                for (int i = 0; i < cblDepartment.Items.Count; i++)
                {
                    if (cblDepartment.Items[i].Selected)
                    {
                        info = new DocumentFileInfo();
                        info.ID = Guid.NewGuid();
                        info.IsFolder = false;
                        info.LastAccessDate = DateTime.Now;
                        info.Level = 0;
                        info.NewFileName = temp;
                        info.OldFileName = fileTitle;
                        info.OrderID = int.Parse(dptOrder.SelectedValue);

                        info.ParentID = Guid.Empty;

                        info.StartDate = startDate;

                        info.FilePath = mapPath + temp;
                        info.FileSize = postedFile.ContentLength / 1024;
                        info.Format = fileExtension.Replace(".", "");
                        info.HasChild = false;
                        info.CreateDate = DateTime.Now;
                        info.CreateUser = User.Identity.Name;
                        info.DepartmentID = cblDepartment.Items[i].Value;
                        Yipusoft.BaseDoc.BLL.FileManager.AddFile(info);
                    }
                }
            }
            else
            {
                lblPrompt.Text = "请您选择要上传的附件";
                return false;
            }

        }

        return true;
    }

  
    protected void YearList_SelectedIndexChanged(object sender, EventArgs e)
    {
        //Bind();
        setParent();
    }
    protected void MonthList_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Bind();
        setParent();
    }
    protected void dptParent_SelectedIndexChanged(object sender, EventArgs e)
    {
        selectDate();

    }
}